<template>
  <div class="inbound-detail" v-loading="loading">
    <div class="page-header">
      <div class="header-content">
        <el-button @click="goBack" icon="ArrowLeft" type="primary" plain>返回列表</el-button>
        <h2>入库详情</h2>
        <div class="header-actions">
          <el-button type="primary" @click="edit">编辑</el-button>
          <el-button type="danger" @click="remove">删除</el-button>
          <el-button @click="print">打印</el-button>
        </div>
      </div>
    </div>

    <el-card shadow="never">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="入库信息" name="base">
          <el-descriptions :column="2" border v-if="detail">
            <el-descriptions-item label="入库类型">{{ detail.inboundType }}</el-descriptions-item>
            <el-descriptions-item label="入库单号">{{ detail.inboundOrderNumber }}</el-descriptions-item>
            <el-descriptions-item label="入库日期">{{ formatDate(detail.inboundDate) }}</el-descriptions-item>
            <el-descriptions-item label="入库仓库">{{ detail.warehouseName }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">{{ detail.remarks || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="入库明细" name="items">
          <div class="tab-toolbar">
            <el-button @click="exportDetails" type="success" icon="Download">导出</el-button>
          </div>
          <el-table :data="detail?.details || []" border stripe>
            <el-table-column type="index" label="#" width="60" />
            <el-table-column prop="itemNumber" label="物品编号" width="160" />
            <el-table-column prop="itemName" label="物品名称" min-width="200" />
            <el-table-column prop="specificationModel" label="规格型号" width="120" />
            <el-table-column prop="unit" label="单位" width="100" />
            <el-table-column prop="brand" label="品牌" width="120" />
            <el-table-column prop="inboundQuantity" label="入库数量" width="120" />
            <el-table-column prop="mainUnitQuantity" label="主单位数量" width="120" />
            <el-table-column prop="batchNumber" label="批次号" width="120" />
            <el-table-column prop="productionDate" label="生产日期" width="140">
              <template #default="{ row }">{{ row.productionDate ? formatDate(row.productionDate) : '-' }}</template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="120" />
          </el-table>
          <div class="summary">
            总量：{{ (detail?.details || []).reduce((s,i)=>s+(i.inboundQuantity||0),0) }}
            总金额：{{ (detail?.details || []).reduce((s,i)=>s+(i.amount||0),0).toFixed(2) }}
          </div>
        </el-tab-pane>
        <el-tab-pane label="操作记录" name="ops">
          <div class="tab-toolbar">
            <el-button>导出</el-button>
          </div>
          <el-timeline>
            <el-timeline-item v-for="r in operationRecords" :key="r.id" :timestamp="new Date(r.operationTime).toLocaleString('zh-CN')">
              <h4>{{ r.operationType }}</h4>
              <p>{{ r.operationContent }}</p>
            </el-timeline-item>
          </el-timeline>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { inboundApi, type InboundDetailDto } from '@/api/inboundApi'
import { ElMessageBox } from 'element-plus'
import * as XLSX from 'xlsx'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const activeTab = ref('base')
const detail = ref<InboundDetailDto | null>(null)

const operationRecords = ref([
  { id: 1, operationType: '新增产品', operationContent: '——', operationTime: new Date().toISOString() },
  { id: 2, operationType: '上传文件', operationContent: '——', operationTime: new Date().toISOString() }
])

onMounted(() => load())

async function load() {
  try {
    loading.value = true
    const id = Number(route.params.id)
    const res = await inboundApi.getById(id)
    if (res.code === 200) detail.value = res.data
    else ElMessage.error(res.message || '加载失败')
  } finally {
    loading.value = false
  }
}

const goBack = () => router.push('/InboundList')
const formatDate = (d: string) => new Date(d).toLocaleDateString('zh-CN')
const exportDetails = () => {
  const data = (detail.value?.details || []).map((x,i)=>({ 序号: i+1, 物品编号: x.itemNumber, 物品名称: x.itemName, 规格型号: x.specificationModel, 单位: x.unit, 品牌: x.brand, 入库数量: x.inboundQuantity, 主单位数量: x.mainUnitQuantity, 批次号: x.batchNumber, 生产日期: x.productionDate ? formatDate(x.productionDate as any) : '-', 金额: x.amount }))
  const ws = XLSX.utils.json_to_sheet(data); const wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, '入库明细'); const ts = new Date().toISOString().slice(0,19).replace(/[:T]/g,'-'); XLSX.writeFile(wb, `入库明细-${ts}.xlsx`)
}

const edit = () => {
  if (!detail.value) return
  router.push(`/InboundCreate?id=${detail.value.id}`)
}

const remove = async () => {
  if (!detail.value) return
  try {
    await ElMessageBox.confirm('确定删除该入库单吗？', '确认', { type: 'warning' })
    const res = await inboundApi.delete(detail.value.id)
    if (res.code === 200 && res.data) {
      ElMessage.success('删除成功')
      router.push('/InboundList')
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (e:any) {
    if (e !== 'cancel') ElMessage.error(e.message || '删除失败')
  }
}

const print = () => {
  window.print()
}
</script>

<style scoped>
.inbound-detail { padding: 20px; }
.page-header { margin-bottom: 16px; }
.header-content { display: flex; align-items: center; gap: 16px; }
.header-content h2 { margin: 0; flex: 1; }
.header-actions { display: flex; gap: 8px; }
.tab-toolbar { display: flex; justify-content: flex-end; margin-bottom: 10px; }
.summary { margin-top: 10px; text-align: right; color: #f56c6c; }
</style> 